﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using seejee_Backendium.Core.Models;
using seejee_Backendium.Data.DbContest;
using seejee_Backendium.Data.Services;
using System;

namespace seejee_Backendium.WEB.Controllers
{
    [ApiController]
    [Route("api/")]
    public class UserController : ControllerBase
    {
        private readonly UserService _userService;
        private readonly ApplicationDbContext _context;
        private readonly IConfiguration _configuration; // 新增字段
        private readonly ILogger<UserController> _logger;

        public UserController(UserService userService, IConfiguration configuration,ILogger<UserController> logger)
        {
            _userService = userService;
            _configuration = configuration;
            _logger = logger; // 
        }

        [HttpPost("login")]
        public IActionResult Login([FromBody] LoginRequest request)
        {
            if (_userService.ValidateUser(request.Username, request.Password))
            {
                // 这里可以生成JWT Token，但为了简化，我们只返回成功信息
                //return Ok(new { Message = "登录成功" });
                return Ok(new { success = true });
            }
            else
            {
                //return Unauthorized(new { Message = "用户名或密码错误" });
                return Ok(new { success = false });
            }
        }
        [HttpGet("user/list")]
        public IActionResult GetUser()
        {
            // 从配置读取连接字符串
            string connStr = _configuration.GetConnectionString("Default");

            using (SqlConnection connection = new SqlConnection(connStr))
            {
                connection.Open();
                string query = "select * from [User] left join Licenses on [User].id=Licenses.user_id;";
                SqlCommand command = new SqlCommand(query, connection);

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    List<Dictionary<string, object>> results = new List<Dictionary<string, object>>();
                    while (reader.Read())
                    {
                        var row = new Dictionary<string, object>();
                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            //row[reader.GetName(i)] = reader.GetValue(i);
                            object value = reader.GetValue(i);
                            // 如果为DBNull或空字符串，则用空格代替
                            if (value == DBNull.Value || (value is string str && string.IsNullOrEmpty(str)))
                            {
                                row[reader.GetName(i)] = " ";
                            }
                            else
                            {
                                row[reader.GetName(i)] = value;
                            }
                           
                        }
                        // 处理权限字段，添加角色显示
                        if (row.ContainsKey("permissions"))
                        {
                            var permissionsValue = row["permissions"]?.ToString();
                            if (permissionsValue == "1")
                            {
                                row["role"] = "用户";
                            }
                            else if (permissionsValue == "0")
                            {
                                row["role"] = "管理员";
                            }
                            else
                            {
                                row["role"] = " ";
                            }
                        }
                        else
                        {
                            row["role"] = " ";
                        }
                        results.Add(row);
                    
                    }
                    return Ok(results); // 返回查询结果
                }
            }
        }
        [HttpGet("user/list/{id}")]
        public IActionResult GetUserById(int id)
        {
            string connStr = _configuration.GetConnectionString("Default");

            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();
                // 多表JOIN查询 
                string sql = @"SELECT u.Id, u.UserName, u.Password, u.RealName,u.user_key,d.ExpiryDate
                FROM [User] u  LEFT JOIN Licenses d ON u.Id = d.user_Id
                WHERE u.Id = @UserId";

                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    cmd.Parameters.AddWithValue("@UserId", id);

                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            var user = new UserInfo
                            {
                                UserId = reader.IsDBNull(reader.GetOrdinal("Id")) ? 0 : reader.GetInt32(reader.GetOrdinal("Id")),
                                UserName = reader.IsDBNull(reader.GetOrdinal("UserName")) ? "" : reader.GetString(reader.GetOrdinal("UserName")),
                                Password = reader.IsDBNull(reader.GetOrdinal("Password")) ? "" : reader.GetString(reader.GetOrdinal("Password")),
                                RealName = reader.IsDBNull(reader.GetOrdinal("RealName")) ? "" : reader.GetString(reader.GetOrdinal("RealName")),
                                UserKey = reader.IsDBNull(reader.GetOrdinal("user_key")) ? "" : reader.GetString(reader.GetOrdinal("user_key")),
                                ExpiryDate = reader.IsDBNull(reader.GetOrdinal("ExpiryDate")) ? DateTime.MinValue : reader.GetDateTime(reader.GetOrdinal("ExpiryDate"))
                            };
                            //return Ok(user);
                            // [[14]]: 返回标准格式
                            return Ok(new
                            {
                                code = 200,
                                message = "success",
                                user
                            });
                        }
                        else
                        {
                            //return NotFound(new { Success = false, Message = "用户不存在" });
                                        return NotFound(new { 
                code = 404, 
                message = "用户不存在" 
            });
                        }
                    }
                }
            }

        }
        [HttpPost("user/update/{UserId}")]
        public IActionResult UpdateUser([FromBody] UserInfo userInfo)
        {
            //try
            //{
            //    string connStr = _configuration.GetConnectionString("DefaultConnection");
            //    using (SqlConnection conn = new SqlConnection(connStr))
            //    {
            //        conn.Open();
            //        string sql = @"UPDATE Users 
            //                   SET UserName = @UserName, 
            //                       Password = @Password, 
            //                       RealName = @RealName,
            //                       UserKey = @UserKey 
            //                   WHERE UserId = @UserId";

            //        using (SqlCommand cmd = new SqlCommand(sql, conn))
            //        {
            //            cmd.Parameters.AddWithValue("@UserId", userInfo.UserId);
            //            cmd.Parameters.AddWithValue("@UserName", userInfo.UserName);
            //            cmd.Parameters.AddWithValue("@Password", userInfo.Password);
            //            cmd.Parameters.AddWithValue("@RealName", userInfo.RealName);
            //            cmd.Parameters.AddWithValue("@UserKey", userInfo.UserKey);

            //            int rowsAffected = cmd.ExecuteNonQuery();

            //            if (rowsAffected > 0)
            //            {
            //                _logger.LogInformation($"用户 {userInfo.UserId} 更新成功"); // 
            //                return Ok(new { Success = true, Message = "用户信息更新成功" });
            //            }
            //            return BadRequest(new { Success = false, Message = "用户不存在或更新失败" });
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    _logger.LogError(ex, "用户更新失败"); // 
            //    return StatusCode(500, new { Success = false, Message = "服务器错误" });
            //}
            string connStr = _configuration.GetConnectionString("DefaultConnection");

            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();

                // 开启事务 
                using (SqlTransaction transaction = conn.BeginTransaction())
                {
                    try
                    {
                        // 更新主表 (Users)
                        string updateMainSql = @"
                        UPDATE [User] 
                        SET UserName = @UserName, 
                            Password = @Password,
                            RealName = @RealName
                        WHERE Id = @UserId";

                        using (SqlCommand cmd = new SqlCommand(updateMainSql, conn, transaction))
                        {
                            cmd.Parameters.AddWithValue("@UserId", userInfo.UserId);
                            cmd.Parameters.AddWithValue("@UserName", userInfo.UserName);
                            cmd.Parameters.AddWithValue("@Password", userInfo.Password);
                            cmd.Parameters.AddWithValue("@RealName", userInfo.RealName);

                            int mainRows = cmd.ExecuteNonQuery();
                            if (mainRows == 0) throw new Exception("用户主表更新失败");
                        }

                        // 更新详情表 (Licenses)
                        string updateDetailSql = @"
                        UPDATE Licenses 
                        SET HashKey = @HashKey, 
                            ExpiryDate = @ExpiryDate
                        WHERE UserId = @UserId";

                        using (SqlCommand cmd = new SqlCommand(updateDetailSql, conn, transaction))
                        {
                            cmd.Parameters.AddWithValue("@UserId", userInfo.UserId);
                            cmd.Parameters.AddWithValue("@HashKey", userInfo.HashKey);
                            cmd.Parameters.AddWithValue("@ExpiryDate", userInfo.ExpiryDate);


                            int detailRows = cmd.ExecuteNonQuery();
                            if (detailRows == 0) throw new Exception("用户详情表更新失败");
                        }

                        // 提交事务
                        transaction.Commit();

                        _logger.LogInformation($"用户 {userInfo.UserId} 更新成功");
                        return Ok(new
                        {
                            Success = true,
                            Message = "用户信息更新成功"
                        });
                    }
                    catch (Exception ex)
                    {
                        // 回滚事务 
                        transaction.Rollback();
                        _logger.LogError(ex, "用户更新失败");
                        return StatusCode(500, new
                        {
                            Success = false,
                            Message = $"更新失败: {ex.Message}"
                        });
                    }
                }
            }
        }
        public class LoginRequest
        {
            public string Username { get; set; }
            public string Password { get; set; }
        }
        public class UserInfo
        {
            public int UserId { get; set; }
            public string UserName { get; set; }
            public string Password { get; set; }
            public string RealName { get; set; }
            public string UserKey { get; set; }
            public string HashKey { get; set; }

            public DateTime ExpiryDate { get; set; }
        }
    }
}
